<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<meta content="user-scalable=no,width=device-width, initial-scale=1" id="viewport" name="viewport" initial-scale="1">

		<script language="javascript" type="text/javascript" src="../js/js/baseJs.js"></script>

	</head>
	<body style="background:#eff6ff">

		<div class="wap-upload-shareholder" id="uploadRequirements" style="display: none;">
			<div class="wap-header">申请股东
				<a class="back" onClick="javascript:window.history.back();return false;"></a>
			</div>
			<div class="zhifubao-qr">
				<img src="../image/zfb_pay.png" />
			</div>
			<div style="font-size:.2rem;text-align: center;">请打开支付宝扫一扫完成转帐并上传转账截图</div>
			<div class="form-bd">
				<div class="input-c">
					<div class="title">姓名:</div>
					<input placeholder="请输入" v-model="name"/>
				</div>
				<div class="input-c">
					<div class="title">申请份额:</div>
					<input placeholder="请输入" type="number" v-model="stockNumber"/>
				</div>
				<!-- <div class="input-c">
					<div class="title">支付宝账号:</div>
					<input placeholder="请输入"  v-model="accountName"/>
				</div> -->

				<div style="display:flex;flex-direction:row">
					<div style="font-size:.28rem;margin: 0 .2rem 0 .6rem;align-items: center;display: flex;min-width: 1.5rem;">转账截图</div>
					<div class="upload-wrap">
					    <div class="box" v-if="imgTempList.length==0">
					        <label class="p dotted">
					            <input type="file" accept="image/*" name="file"
					                   @change="onChooseImage($event)">
					            <img src="../image/add_ico.png" alt="">
					        </label>
					    </div>
					    <template v-for="(imgIndex,imgItem) in imgTempList">
					        <div class="box">
					            <div class="image-c">
					                <img :src="imgItem">
					                <div class="delete" @click.stop="deleteImg(imgIndex)">
					                    <img src="../image/close_ico.png" alt="">
					                </div>
					            </div>
					        </div>
					    </template>
					</div>
				</div>
<!-- 				<div @click="onUploadImg">上传</div>  -->
				<div class="wap-comfirm-button" @click="saveFeedBack()">我已打款，成为股东</div>
			</div>
			<!--  压缩图片用的  -->
		    <canvas id="compressCanvas" style="position: fixed; z-index: -1; opacity: 0; top: -100%; left: -100%"></canvas>
		</div>
		<script src="../js/js/rem_fix.js"></script>
		<script src="../js/js/common.js"></script>
		<script type="text/javascript">
			var token = getCookie("userToken");
			var userId = getCookie("userId");
			console.log(token)
			console.log(userId)
			var loginUrl = "../userBundle/login.mobile.html" + "?" + "../userBundle/becomeShareholder.mobile.html";
			console.log(loginUrl)
			if (!token || !userId) {
				window.location.href = loginUrl;
			}
			var uploadPayInfoApp = new Vue({
				el: '#uploadRequirements',
				data: {
					name: "",
					stockNumber: null,
					accountName:'',
					isDoingSaveFeedBack:false,

					imgTempList: [], //图片临时路径列表
					imgUrlList:[],//存放七牛返回地址列表
            		isUploading: false, //是否正在上传

            		qiniuData: {
			          key: "",
			          token: ""
			        },
			        upload_qiniu_addr:'',
				},
				ready: function() {
					$("#uploadRequirements").show();
					var data={
			            client: 1,
			            token: token,
			            userId: userId
			          }
			          pushData("/qiniu/get_token ",data,function(res){
			            if(res.state){
			              this.qiniuData.token=res.data.result;
			              console.log(res)
			            }else if (res.errorCode == 008) {
						  window.location.href = loginUrl;
						}else{
			              alert(res.message)
			            } 
			          }.bind(this));
			          pushData("/qiniu/get_image_rul",data,function(res){
			            if(res.state){
			              this.upload_qiniu_addr=res.data.url;
			              console.log(res)
			            }else if (res.errorCode == 008) {
								window.location.href = loginUrl;
						}else{
			              alert(res.message)
			            } 
			          }.bind(this));

				},

				methods: {
					saveFeedBack: function() {
						if (this.isDoingSaveFeedBack) {
							return;
						}
						if (!this.name) {
							alert("姓名不能为空")
							return
						}
						if (!this.stockNumber) {
							alert("申购份数不能为空")
							return
						}
						if (this.stockNumber<=0) {
							alert("申购份数不能小于1")
							return
						}
						this.isDoingSaveFeedBack = true;

						var url = "/stockApply/saveStockApply";
						var data = {
							client: 1,
							images: "",
							name: this.name,
							stockNumber:this.stockNumber,
							token: token,
							userId: userId
						}
						if(this.imgUrlList.length>1){
							data.images=this.imgUrlList.join(',')
						}else{
							data.images=this.imgUrlList.join('')
						}
						console.log(data)
						pushData(url, data, function(res) {
							this.isDoingSaveFeedBack = false;
							if (res.state) {
								window.location.href="./successPage.mobile.html"
							} else if (res.errorCode == 008) {
								window.location.href = loginUrl;
							} else {
								alert(res.message);
							}
						}.bind(this));
					},
					//选择图片
		            onChooseImage: function (event) {
		                var that = this;
                        that.imgUrlList=[]; 
		                //判断图片数量是否已上限
		                var currentImgTempArray = that.imgTempList;
		                if (currentImgTempArray.length >= 5) {
		                    alert("最多上传5张图片");
		                    return false;
		                }

		                //使用FileReader对文件对象进行操作
		                var reader = new FileReader();
		                reader.readAsDataURL(event.target.files[0]); //将读取到的文件编码成Data URL
		                console.log(event.target.files[0])

		                reader.onload = function () { //读取完成时
		                    var replaceSrc = reader.result; //文件输出的内容
                            //console.log(reader)
		                    //压缩图片处理
		                    var image = new Image();
		                    image.src = replaceSrc;
		                    image.onload = function () {
		                        //获取图片初始宽高
		                        var width = image.width;
		                        var height = image.height;
		                        //判断图片宽度，再按比例设置宽度和高度的值
		                        if (width > 1024) {
		                            width = 1024;
		                            height = Math.ceil(1024 * (image.height / image.width));
		                        }

		                        //将图片重新画入canvas中
		                        var canvas = document.getElementById("compressCanvas");
		                        var context = canvas.getContext("2d");
		                        canvas.width = width;
		                        canvas.height = height;
		                        context.beginPath();
		                        context.fillStyle = "#ffffff";
		                        context.fillRect(0, 0, width, height);
		                        context.fill();
		                        context.closePath();
		                        context.drawImage(image, 0, 0, width, height);
		                        replaceSrc = canvas.toDataURL("image/jpeg"); //canvas转DataURL(base64格式)

		                        //将压缩后的路径 追加到临时路径数组中
		                        var totalList = [];
		                        if (currentImgTempArray.length > 0) {
		                            totalList = currentImgTempArray.concat(replaceSrc);
		                        } else {
		                            totalList[0] = replaceSrc;
		                        }
		                        
		                        that.imgTempList = totalList;
		                        that.onUploadImg()
		                        //console.log(that.imgTempList)
		                    };
		                };

		            },
		            onUploadImg: function () {
		                var that = this;
		                var imgTempList = that.imgTempList;
		                if (imgTempList.length > 0) {

		                    that.isUploading = true; //正在上传 显示遮罩层 防止连续点击

		                    var countNum = 0; //计算数量用的 判断上传到第几张图片了

		                    //map循环遍历上传图片
		                    imgTempList.map(function (imgItem, imgIndex) {
		                        var files = that.dataURLtoFile(imgItem, 'pj' + Date.now() + '.jpg'); //DataURL转File
		                        console.log(files)
								that.qiniuData.key=files.name;
                                var formData = new FormData();
                                formData.append('token',that.qiniuData.token)
                                formData.append('key',that.qiniuData.key)//key为名称
                                formData.append('file',files)
							    // formData.token=that.qiniuData.token;
							    //
								// formData.append("k1", "v1")							
								// formData.get("k1"); // "v1"
		                        console.log(formData)
		                        $.ajax({
		                        	type: 'POST',
							        url: 'http://upload.qiniup.com',
							        contentType: false,
							        data: formData,
							        processData: false,
							        async :false,//设置格式为同步非异步 不然可能会报错无法存储到临时变量/对象
							        dataType:'json',
							        success: function (r) {
							            console.log(r);
							            that.imgUrlList.push(that.upload_qiniu_addr +"/"+r.key);
							            console.log(that.upload_qiniu_addr +"/"+r.key)
							        },
							        error: function (r) {
							            console.log(r);
							        }
		                        })
		                        //用axios上传，
		       //                  axios({
		       //                      method: "POST",
		       //                      //url: "http://www.clluo.com:8060/uploadImg",
									// url: "http://图片上传路径",
		       //                      data: formdata,
		       //                      headers: {
		       //                          "Content-Type": "multipart/form-data"
		       //                      }
		       //                  }).then(function (res) {
		       //                      console.log(res);
		       //                      countNum++;
		       //                      console.log("第 " + countNum + " 张图片上传完成");
		       //                      //图片全部上传完后去掉遮罩层
		       //                      if (countNum >= imgTempList.length) {
		       //                          that.isUploading = false;
		       //                      }

		       //                      //没必要的代码 👇
		       //                      var list = [];
		       //                      if (that.successPath.length > 0) {
		       //                          list = that.successPath.concat(res.data.path);
		       //                      } else {
		       //                          list[0] = res.data.path;
		       //                      }
		       //                      that.successPath = list;

		       //                  }).catch(function (error) {
		       //                      console.error(error);
		       //                  });
		                    });
		                }
		            },
					
		            //删除某张图片
		            deleteImg: function (idx) {
		                var that = this;
		                that.imgTempList.splice(idx, 1);
		            },
				             /**
		             * 将base64转换为文件
		             * @dataUrl base64路径地址
		             * @fileName 自定义文件名字
		             * */
		            dataURLtoFile: function (dataUrl, fileName) {
		                var arr = dataUrl.split(','), mime = arr[0].match(/:(.*?);/)[1],
		                    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
		                while (n--) {
		                    u8arr[n] = bstr.charCodeAt(n);
		                }
		                return new File([u8arr], fileName, {type: mime});
		            },
				}
			})
		</script>

	</body>
</html>
